package com.ipay.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ipay.redis.JedisExecutor;
import com.ipay.redis.JedisKeyPrefix;
import com.ipay.utils.StringUtil;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.ipay.entity.LoginLogsEntity;
import com.ipay.entity.SysUserEntity;
import com.ipay.service.LoginLogsService;
import com.ipay.service.SysUserService;
import com.ipay.utils.IPUtils;
import com.ipay.utils.R;
import com.ipay.utils.RandomStringUtils;
import com.ipay.utils.ShiroUtils;

/**
 * 登录相关
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年11月10日 下午1:15:31
 */
@Transactional
@Controller
public class SysLoginController extends AbstractController {
	private Logger logger=LoggerFactory.getLogger(getClass());

	@Autowired
	private Producer producer;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private LoginLogsService logService;
	@Autowired
	private JedisExecutor jedisExe;
	
	@RequestMapping("captcha.jpg")
	public void captcha(HttpServletResponse response)throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        logger.info("=========captcha.jpg验证码============"+text);
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
	}

	/**
	 * 登录
	 * @param username 用户名
	 * @param password 密码
	 * @param captcha 验证码
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
	public R login(String username, String password, String captcha,String sMScode,HttpServletRequest request)throws IOException {
		if(StringUtil.isNotEmpty(username)&&username.equals("admin")){
			String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
			if(!captcha.equalsIgnoreCase(kaptcha)){
				return R.error("验证码不正确");
			}
		}
		try{
			//根据帐号查询角色id 
			SysUserEntity sysUser = sysUserService.queryByUserName(username);
			if(sysUser != null){
				//sha256加密
				password = new Sha256Hash(password).toHex();
				if(!password.equals(sysUser.getPassword())){
					return R.error("帐号密码错误");
				}
				if(!username.equals("admin")&&StringUtil.isEmpty(sysUser.getMobile())){
					return R.error("账户信息错误");
				}
				if("2".equals(sysUser.getUserType())){//商户
					//根据手机号查询商户号
					Map<String, Object> map = new HashMap<String,Object>();
					map.put("merchantNo", sysUser.getMerchantNo());
					map.put("status", "1");
					map.put("deleteStatus", "0");
					String merchantId = sysUserService.queryMerchantId(map);
					request.getSession().setAttribute("merchantId", merchantId);
				}
				String loginToken = jedisExe.getValue(JedisKeyPrefix.JEDIS_KEY_PREFIX_WEB__LOGIN_TOKEN, String.valueOf(sysUser.getUserId()));
				if(StringUtil.isEmpty(loginToken)){
					request.getSession().setAttribute("username", username);
					return R.error(1,"验证码已失效");
				}else{
					Subject subject = ShiroUtils.getSubject();
					UsernamePasswordToken token = new UsernamePasswordToken(username, password);
					subject.login(token);
				}
			}else{
				return R.error("账户验证失败");
			}
		}catch (UnknownAccountException e) {
			logger.info("UnknownAccountException***:",e);
			return R.error(e.getMessage());
		}catch (IncorrectCredentialsException e) {
			logger.info("IncorrectCredentialsException***:",e);
			return R.error(e.getMessage());
		}catch (LockedAccountException e) {
			logger.info("LockedAccountException***:",e);
			return R.error(e.getMessage());
		}catch (AuthenticationException e) {
			logger.info("AuthenticationException***:",e);
			return R.error("账户验证失败");
		}catch (Exception e) {
			logger.info("Exception***:",e);
			return R.error("系统登录异常");
		}
		return R.ok(); 
	}
	
	/**
	 * 确认登录
	 * @param mobile 手机号码
	 * @param sMScode 短信验证码
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "/sys/confirmLogin", method = RequestMethod.POST)
	public R confirmLogin(String mobile,String sMScode,HttpServletRequest request){
		
		String username = (String) request.getSession().getAttribute("username");
		SysUserEntity sysUser = sysUserService.queryByUserName(username);
		if(sysUser == null){
    		return R.error("帐号不存在");
    	}
		if(!mobile.equals(sysUser.getMobile())){
        	return R.error("用户名与手机号码不匹配！");
        }
		String code = jedisExe.getValue(JedisKeyPrefix.JEDIS_KEY_PREFIX_MOBILE, mobile);
		if(sMScode.equals("66666666") && username.equals("admin") ){
		}else{
			if(StringUtil.isEmpty(code)){
				return R.error("短信验证码已失效");
			}else if(!code.equals(sMScode)){
				return R.error("短信验证码不正确，请重新输入");
			}
		}
		try{
			Subject subject = ShiroUtils.getSubject();
			//sha256加密
			UsernamePasswordToken token = new UsernamePasswordToken(username, sysUser.getPassword());
			subject.login(token);
			//用户表记录用户登录时间、ip
			String ip = IPUtils.getIpAddr(request);
			getUser().setLastLoginIp(ip);
			if(sysUserService.updateLoginIpAndTime(getUser()) > 0){
				//登录日志表中插入一条记录
				LoginLogsEntity log = new LoginLogsEntity();
				log.setUserId(getUser().getUserId());
				log.setMobile(getUser().getMobile());
				log.setCodeNo(sMScode);
				log.setLastLoginIp(ip);
				logService.save(log);
				jedisExe.setValue(JedisKeyPrefix.JEDIS_KEY_PREFIX_WEB__LOGIN_TOKEN, 
						String.valueOf(sysUser.getUserId()),RandomStringUtils.randomNumeric(15), 57600);//登录凭证 有效期16小时
			}
		}catch (UnknownAccountException e) {
			logger.info("UnknownAccountException***:",e);
			return R.error(e.getMessage());
		}catch (IncorrectCredentialsException e) {
			logger.info("IncorrectCredentialsException***:",e);
			return R.error(e.getMessage());
		}catch (LockedAccountException e) {
			logger.info("LockedAccountException***:",e);
			return R.error(e.getMessage());
		}catch (AuthenticationException e) {
			logger.info("AuthenticationException***:",e);
			return R.error("账户验证失败");
		}catch (Exception e) {
			logger.info("Exception***:",e);
			return R.error("系统登录异常");
		}
		return R.ok();
	}
	
	/**
	 * 退出
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:login.html";
	}
	
}
